#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    socket = new QUdpSocket(this);
    connect(socket, &QUdpSocket::connected, this, &MainWindow::sendData);
    connect(socket, &QUdpSocket::readyRead, this, &MainWindow::readData);

    timer = new QTimer(this);
    timer->start(10000);
    connect(timer, &QTimer::timeout, this, &MainWindow::timeout);
}

MainWindow::~MainWindow()
{

}

void MainWindow::timeout()
{
    qDebug() << "timeout";
    socket->abort();
    socket->connectToHost("ntp1.aliyun.com", 123);
}

void MainWindow::sendData()
{
    qint8 LI = 0;
    qint8 VN = 3;
    qint8 MODE = 3;
    qint8 STRATUM = 0;
    qint8 POLL = 4;
    qint8 PREC = -6;
    QDateTime epoch(QDate(1900, 1, 1), QTime(0, 0, 0));
    qint32 second = quint32(epoch.secsTo(QDateTime::currentDateTime()));

    qint32 temp = 0;
    QByteArray timeRequest(48, 0);
    timeRequest[0] = (LI << 16) | (VN << 3) | MODE;
    timeRequest[1] = STRATUM;
    timeRequest[2] = POLL;
    timeRequest[3] = PREC & 0XFF;
    timeRequest[5] = 1;
    timeRequest[9] = 1;
    timeRequest[40] = (temp = (second & 0xff000000) >> 24);
    temp = 0;
    timeRequest[41] = (temp = (second & 0x00ff0000) >> 16);
    temp = 0;
    timeRequest[42] = (temp = (second & 0x0000ff00) >> 8);
    temp = 0;
    timeRequest[43] = (second & 0x000000ff);

    socket->write(timeRequest);
    qDebug() << "sendData";
}

void MainWindow::readData()
{
    QByteArray newTime;
    QDateTime epoch(QDate(1900, 1, 1), QTime(0,0,0));
    QDateTime unixStart(QDate(1970, 1, 1), QTime(0, 0, 0));

    while(socket->hasPendingDatagrams())
    {
        newTime.resize(socket->pendingDatagramSize());
        socket->read(newTime.data(), newTime.size());
    }

    QByteArray transmitTimeStamp;
    transmitTimeStamp = newTime.right(8);
    quint32 seconds = transmitTimeStamp.at(0);
    quint8 temp = 0;

    for(int i=0; i<=3; i++)
    {
        seconds <<= 8;
        temp = transmitTimeStamp.at(i);
        seconds += temp;
    }

    QDateTime dateTime;
    uint secs = seconds - epoch.secsTo(unixStart);
    dateTime.setTime_t(secs);
    socket->disconnectFromHost();

    if(dateTime.isValid())
        qDebug() << dateTime.toString("yyyy-MM-dd HH:mm:ss zzz");
    else
        qDebug() << "unvalid";
}



